package StudyCode.summary.myfile;

import java.io.*;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class SerializingObjectsMoreEfficiently {
	public static void main(String[] args) {
		SerializingObjectsMoreEfficiently example = new SerializingObjectsMoreEfficiently();
		example.start();
	}

	private void start() {
		MyClass1 settings = new MyClass1("序列化对象");
		saveSettings(settings, "settingsExternalizable.bin");
		MyClass1 loadedSettings = loadSettings("settingsExternalizable.bin");
		if (loadedSettings != null)
			System.out.println("序列化对象跟反序列化对象是否相同? :" + loadedSettings.equals(settings));

	}

	private void saveSettings(MyClass1 settings,
	                          String filename) {
		try {
			FileOutputStream fos = new FileOutputStream(filename);
			try (ObjectOutputStream oos = new ObjectOutputStream(fos)) {
				oos.writeObject(settings);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private MyClass1 loadSettings(String filename) {
		try {
			FileInputStream fis = new FileInputStream(filename);
			ObjectInputStream ois = new ObjectInputStream(fis);
			return (MyClass1) ois.readObject();
		} catch (IOException | ClassNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}
}

class MyClass1 implements Externalizable {
	private String title;

	public MyClass1() {
	}

	@Override
	public void writeExternal(ObjectOutput out) throws IOException {
		out.writeUTF(title);
	}

	@Override
	public void readExternal(ObjectInput in) throws IOException,
			ClassNotFoundException {
		title = in.readUTF();
	}

	public MyClass1(String title) {
		this.title = title;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}
}
